<template>
  <div class="map-box">
    <div class="map" id="map"></div>
    <div class="export-btn">
      <a id="image-download" download="map.png"></a>
      <el-button type="primary" size="small" @click="exportPNG">Download PNG</el-button>
    </div>
  </div>
</template>

<script>
import "ol/ol.css";
import Map from "ol/Map";
import View from "ol/View";
import { TileArcGISRest } from "ol/source";
import { Tile as TileLayer } from "ol/layer";

import CONSTANT from "@/config/constant.js";

export default {
  name: "exportPNG",

  data() {
    return {
      map: null
    };
  },

  methods: {
    init() {
      this.map = new Map({
        layers: [
          new TileLayer({
            source: new TileArcGISRest({
              url: CONSTANT.GIS_URL,
              crossOrigin: "anonymous"
            })
          })
        ],
        target: "map",
        view: new View({
          center: [113.0567, 23.67537],
          maxZoom: 18,
          minZoom: 8,
          zoom: 13,
          projection: "EPSG:4326"
        })
      });
    },

    //将地图导出为PNG
    exportPNG() {
      this.map.once("rendercomplete", () => {
        var mapCanvas = document.createElement("canvas");
        var size = this.map.getSize();
        mapCanvas.width = size[0];
        mapCanvas.height = size[1];
        var mapContext = mapCanvas.getContext("2d");
        Array.prototype.forEach.call(
          document.querySelectorAll(".ol-layer canvas"),
          function(canvas) {
            if (canvas.width > 0) {
              var opacity = canvas.parentNode.style.opacity;
              mapContext.globalAlpha = opacity === "" ? 1 : Number(opacity);
              var transform = canvas.style.transform;
              // Get the transform parameters from the style's transform matrix
              var matrix = transform
                .match(/^matrix\(([^\(]*)\)$/)[1]
                .split(",")
                .map(Number);
              // Apply the transform to the export map context

              CanvasRenderingContext2D.prototype.setTransform.apply(
                mapContext,
                matrix
              );
              mapContext.drawImage(canvas, 0, 0);
            }
          }
        );
        if (navigator.msSaveBlob) {
          // link download attribuute does not work on MS browsers
          navigator.msSaveBlob(mapCanvas.msToBlob(), "map.png");
        } else {
          var link = document.getElementById("image-download");
          link.href = mapCanvas.toDataURL();
          link.click();
        }
      });
      this.map.renderSync();
    }
  },

  mounted() {
    this.init();
  }
};
</script>

<style lang="less" scoped>
.map-box {
  height: 100%;
  position: relative;
  .map {
    height: 100%;
  }
  .export-btn {
    position: absolute;
    right: 15px;
    top: 15px;
  }
}
</style>